package com.example.pcbcsmbackend.controller;

import com.example.pcbcsmbackend.entity.Category;
import com.example.pcbcsmbackend.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/category")
@CrossOrigin(origins = "http://localhost:8080")
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    // 获取所有分类
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllCategories() {
        Map<String, Object> response = new HashMap<>();
        List<Category> categories = categoryService.getAllCategories();
        response.put("success", true);
        response.put("categories", categories);
        return ResponseEntity.ok(response);
    }
    
    // 获取顶级分类
    @GetMapping("/top")
    public ResponseEntity<Map<String, Object>> getTopLevelCategories() {
        Map<String, Object> response = new HashMap<>();
        List<Category> categories = categoryService.getTopLevelCategories();
        response.put("success", true);
        response.put("categories", categories);
        return ResponseEntity.ok(response);
    }
    
    // 根据父分类获取子分类
    @GetMapping("/children/{parentId}")
    public ResponseEntity<Map<String, Object>> getCategoriesByParent(@PathVariable Integer parentId) {
        Map<String, Object> response = new HashMap<>();
        List<Category> categories = categoryService.getCategoriesByParent(parentId);
        response.put("success", true);
        response.put("categories", categories);
        return ResponseEntity.ok(response);
    }
    
    // 根据ID获取分类
    @GetMapping("/{categoryId}")
    public ResponseEntity<Map<String, Object>> getCategoryById(@PathVariable Integer categoryId) {
        Map<String, Object> response = new HashMap<>();
        Optional<Category> category = categoryService.findById(categoryId);
        if (category.isPresent()) {
            response.put("success", true);
            response.put("category", category.get());
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "分类不存在");
            return ResponseEntity.notFound().build();
        }
    }
    
    // 添加分类（管理员功能）
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addCategory(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String categoryName = (String) request.get("categoryName");
            Integer parentId = request.get("parentId") != null ? 
                              Integer.parseInt(request.get("parentId").toString()) : null;
            String description = (String) request.get("description");
            
            Category category = categoryService.addCategory(categoryName, parentId, description);
            response.put("success", true);
            response.put("message", "分类添加成功");
            response.put("category", category);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 更新分类（管理员功能）
    @PutMapping("/update/{categoryId}")
    public ResponseEntity<Map<String, Object>> updateCategory(@PathVariable Integer categoryId, @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 先查找现有分类
            Optional<Category> existingCategoryOpt = categoryService.findById(categoryId);
            if (!existingCategoryOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "分类不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            Category category = existingCategoryOpt.get();
            
            // 更新分类信息
            if (request.get("categoryName") != null) {
                category.setCategoryName((String) request.get("categoryName"));
            }
            if (request.containsKey("parentId")) {
                Object parentIdObj = request.get("parentId");
                category.setParentId(parentIdObj != null ? Integer.parseInt(parentIdObj.toString()) : null);
            }
            if (request.get("description") != null) {
                category.setDescription((String) request.get("description"));
            }
            
            Category updatedCategory = categoryService.updateCategory(category);
            response.put("success", true);
            response.put("message", "分类更新成功");
            response.put("category", updatedCategory);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 删除分类（管理员功能）
    @DeleteMapping("/{categoryId}")
    public ResponseEntity<Map<String, Object>> deleteCategory(@PathVariable Integer categoryId) {
        Map<String, Object> response = new HashMap<>();
        try {
            categoryService.deleteCategory(categoryId);
            response.put("success", true);
            response.put("message", "分类删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 批量删除分类（管理员功能）
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteCategories(@RequestBody List<Integer> categoryIds) {
        Map<String, Object> response = new HashMap<>();
        try {
            categoryService.batchDeleteCategories(categoryIds);
            response.put("success", true);
            response.put("message", "批量删除分类成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 